#most written by Nie Le
import serial
import signal
import wave
import sys

if __name__ == '__main__':
    port = "COM1"
    bps = 500000
    ser = serial.Serial(port, bps)

    count = 0
    frame = bytes()
    frames = []
    
    def signal_handler(signal, frame):
        wf = wave.open('test.wav', 'wb')
        wf.setnchannels(1)
        wf.setsampwidth(2)
        wf.setframerate(48000)
        wf.writeframes(b''.join(frames))
        wf.close()
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)
    
    while True:
        data = ser.read()
        frame += b'\x80'
        frame += data
        count += 1

        if count % 4096 == 0:
            frames.append(frame)
            frame = bytes()
            count = 0
                

